package com.snails.net.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.content.FileProvider;

import java.io.File;

/**
 * apk安装
 * @author lawrence
 * @date 2019-04-16 10:26
 */
public final class ApkUtil {

    private ApkUtil() { }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     *
     * SDK>=26时，要确保已有权限
     *      {@code <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />}
     */
    private static Intent install(final Context ctx, final File file, final boolean isNewTask) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri dataUri = null;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            // android7.0以下直接安装
            dataUri = Uri.fromFile(file);
        } else {
            final String authority = ctx.getPackageName() + ".snails.fileprovider";
            // 参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            dataUri = FileProvider.getUriForFile(ctx, authority, file);
            // 添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        ctx.grantUriPermission(ctx.getPackageName(), dataUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(dataUri, "application/vnd.android.package-archive");
        if (isNewTask) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); }
        return intent;
    }

    /**
     * 安装apk
     */
    public static void install(final Activity activity, final File file, final int requestCode) {
        if (!FileUtil.isFileExists(file)) return;

        final Context appCtx = activity.getApplicationContext();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasInstallPermission = appCtx.getPackageManager().canRequestPackageInstalls();
            if (hasInstallPermission) {
                final Intent intent = install(appCtx, file, true);
                activity.startActivity(intent);
            } else {
                //跳转至“安装未知应用”权限界面，引导用户开启权限
                Uri selfPackageUri = Uri.parse("package:" + appCtx.getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, selfPackageUri);
                activity.startActivityForResult(intent, requestCode);
            }
        } else {
            final Intent intent = install(appCtx, file, true);
            activity.startActivity(intent);
        }
    }

}
